package com.mail;

import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.DAO.DaoImpl;
import com.carpark.ejb.Model.ClientsModel;
import com.webservice.DaoSingleObject;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import validator.ValidationBean;

/**
 *
 * @author Piotr
 */
@ManagedBean
@RequestScoped
public class ForgotPassword implements Serializable {

    private static final long serialVersionUID = 1L;
    @Size(min = 1, max = 50, message = "Zły e-mail")
    @Pattern(regexp = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$", message = "Zły e-mail")
    private String email = null;
   private final DAO dao = getSingleDao();
  public  DaoSingleObject dso;
    private String password;
    private static final String ERROR_FORGOT_PASSWORD = "Błąd podczas przypomnienia hasła.";
    private static final String WRONG_EMAIL = "Podałeś zły email.";

    public String changePassword() {
        if (isCorrectMail()) {
            try {
                createNewPassword();
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(ForgotPassword.class.getName()).log(Level.SEVERE, "[CarPark] Password coding error.", ex);
                createErrorMessage(ERROR_FORGOT_PASSWORD);
                return "/forgotPassword.xhtml";
            }
            try {
                sendPassword();
            } catch (NamingException ex) {
                Logger.getLogger(ForgotPassword.class.getName()).log(Level.SEVERE, "[CarPark] NamingException while mail sended.", ex);
                return "/forgotPassword.xhtml";
            }
            return "/passwordReminded.xhtml";
        }
        createErrorMessage(WRONG_EMAIL);
        return "/forgotPassword.xhtml";
    }

    private boolean isCorrectMail() {
        return getClientByEmail() != null;
    }

    private ClientsModel getClientByEmail() {
        return dao.getClientByEmail(email);
    }

    private void createNewPassword() throws NoSuchAlgorithmException {
        ClientsModel client = getClientByEmail();
        password = generateNewPassword();
        String codedPassword = codePassword(password);
        client.setPassword(codedPassword);
        dao.updateClient(client);
    }
  public DAO getSingleDao() {
        if (this.dso == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            this.dso = (DaoSingleObject) app.evaluateExpressionGet(context, "#{daoSingleObject}", DaoSingleObject.class);
        }
        return this.dso.getDao();
    }
    private void sendPassword() throws NamingException {
        Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] Mail with password sended to: {0}. Passowrd: {1}", new Object[]{email, password});
        Email email = new Email(this.email, "car20park13", "Przypomnienie hasła", "Witaj. Oto twoje nowe hasło do zalogowania: "+password);
        try {
            email.send();
        } catch (Exception ex) {
            Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] Mail not sended - exception during sending.", ex);
        }
    }

    private String generateNewPassword() {
        char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        return sb.toString();
    }

    private String codePassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte byteData[] = md.digest();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }
    
    private void createErrorMessage(String info) {
        FacesMessage msg = new FacesMessage();
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        msg.setSummary(info);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
  
}
